#!/usr/bin/env python
# -*- coding:utf-8 -*-

from django.shortcuts import render
import json
from django.http import HttpResponse
from init_db import NSDb
import time
from django.views.decorators.csrf import csrf_exempt

db = NSDb()
db.run_all_init_func()


def index(request):
    serverList = db.get_server_list()
    return render(request, 'index.html', {"serverList": serverList})


def detail(request):
    ip = request.GET.get('ip')
    return render(request, 'detail.html', {"serverIp": ip})


def getServerInfo(request):
    ip = request.GET.get('ip')
    dataArr = db.get_info_list_by_ip(ip, 0, 1)
    resp = {}
    if len(dataArr) > 0:
        resp = dataArr[0]

    return HttpResponse(json.dumps(resp), content_type="application/json")


def getDiskInfo(request):
    ip = request.GET.get('ip')
    dataArr = db.get_disk_info_by_ip(ip)
    resp = {}
    if len(dataArr) > 0:
        resp = dataArr[0]

    return HttpResponse(json.dumps(resp), content_type="application/json")


def getDiskIOInfo(request):
    ip = request.GET.get('ip')
    num = request.GET.get('num')
    dataArr = db.get_disk_list_by_ip(ip, 0, num)
    resp = {}

    if len(dataArr) > 0:
        resp['dateArr'] = []
        resp['ioArr'] = dataArr[1]
        for item in dataArr[len(dataArr) - 1]:
            cpu_date_time = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(item))
            resp['dateArr'].append(cpu_date_time)

    return HttpResponse(json.dumps(resp), content_type="application/json")


def getCPUInfo(request):
    ip = request.GET.get('ip')
    num = request.GET.get('num')
    dataArr = db.get_cpu_list_by_ip(ip, 0, num)
    resp = {}
    if len(dataArr) > 0:
        resp['usageArr'] = dataArr[0]
        resp['userArr'] = dataArr[1]
        resp['niceArr'] = dataArr[2]
        resp['systemArr'] = dataArr[3]
        resp['iowaitArr'] = dataArr[4]
        resp['dateArr'] = []
        for item in dataArr[len(dataArr) - 1]:
            cpu_date_time = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(item))
            resp['dateArr'].append(cpu_date_time)

    return HttpResponse(json.dumps(resp), content_type="application/json")


def getLoadInfo(request):
    ip = request.GET.get('ip')
    num = request.GET.get('num')
    dataArr = db.get_load_list_by_ip(ip, 0, num)
    resp = {}

    if len(dataArr) > 0:
        resp['dateArr'] = []
        resp['loadArr'] = dataArr[0]
        for item in dataArr[len(dataArr) - 1]:
            cpu_date_time = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(item))
            resp['dateArr'].append(cpu_date_time)

    return HttpResponse(json.dumps(resp), content_type="application/json")


def getMemInfo(request):
    ip = request.GET.get('ip')
    num = request.GET.get('num')
    dataArr = db.get_mem_list_by_ip(ip, 0, num)
    resp = {}

    if len(dataArr) > 0:
        resp['dateArr'] = []
        resp['usageArr'] = dataArr[0]
        resp['freeArr'] = dataArr[1]
        resp['swapUsedArr'] = dataArr[2]
        resp['swapFreeArr'] = dataArr[3]
        for item in dataArr[len(dataArr) - 1]:
            cpu_date_time = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(item))
            resp['dateArr'].append(cpu_date_time)

    return HttpResponse(json.dumps(resp), content_type="application/json")


@csrf_exempt
def update(request):
    resp = {
        'isSucc': False,
        'errorMessage': ''
    }

    try:
        if request.method == 'POST':
            data = json.loads(request.body)

            hostname = ''
            ip = data['ip']
            load = data['load']
            baseCpu = ''
            baseMem = ''
            baseSwap = ''
            osname = ''
            kernel = ''
            uptime = data['uptime']

            if data.has_key('platform'):
                platform = data['platform']
                hostname = platform['hostname']
                kernel = platform['kernel']
                osname = platform['osname']

            if data.has_key('cpu_usage'):
                cpu = data['cpu_usage']
                db.add_cpu_info(hostname, ip, cpu['user_cpu'], cpu['nice_cpu'], cpu['system_cpu'], cpu['iowait_cpu'],
                                cpu['idle_cpu'], cpu['usage_cpu'], load)
                baseCpu = cpu['usage_cpu']

            if data.has_key('mem'):
                mem = data['mem']
                db.add_mem_info(hostname, ip, mem['total'], mem['usage'], mem['free'], mem['swap_total'], mem['swap_used'],
                                mem['swap_free'], mem['percent'])
                baseMem = mem['percent']

            db.add_base_info(hostname, ip, baseCpu, baseMem, baseSwap, osname, kernel, uptime)

            resp['isSucc'] = True
        else:
            resp['isSucc'] = False
            resp['errorMessage'] = '只能接收POST请求'
    except Exception as e:
        print e
        resp['isSucc'] = False
        resp['errorMessage'] = e.message
        raise e

    return HttpResponse(json.dumps(resp), content_type="application/json")

